'use strict';

const Controller = require('egg').Controller;
const path = require('path');
const fs = require('fs');
const Pump = require('mz-modules/pump'); // 此模块解决上传超时卡死
const sendToWormhole = require('stream-wormhole');

class FileController extends Controller {
  // 单文件上传
  async upload() {
    const { ctx } = this;
    // 获取文件流
    const stream = await ctx.getFileStream();
    // 定义文件名
    // console.log(path.basename(stream.filename.toLowerCase()));// 文件名
    const extname = path.extname(stream.filename.toLowerCase());
    const filename = `yzq_${new Date().getTime()}${extname}`;
    // 目标文件
    const target = path.join('app/public/images', filename);
    const writeStream = fs.createWriteStream(target, 'utf-8');
    try {
      // 异步把文件流 写入
      await Pump(stream, writeStream);
      ctx.helper.res_success({ url: `${ctx.request.header.host}/public/images/${filename}`, fields: stream.fields });
    } catch (error) {
      // 如果出现错误，关闭管道
      await sendToWormhole(stream);
      ctx.helper.res_fail(error, '文件上传失败');
    }
  }

  async uploads() {
    const { ctx } = this;
    // autoFields: true 表示除了文件的其它字段
    const parts = ctx.multipart({ autoFields: true });
    const files = [];
    let stream;
    // 循环获取数据流
    while ((stream = await parts()) != null) {
      console.log(stream);
      if (stream.length) {
        // part 是上传的文件流
        console.log('field: ' + stream.fieldname);
      } else {
        if (!stream.filename) {
          return;
        }
        const extname = path.extname(stream.filename.toLowerCase());
        const filename = `yzq_${new Date().getTime()}${extname}`;
        const target = path.join('app/public/images', filename);
        const writeStream = fs.createWriteStream(target);
        await Pump(stream, writeStream);
        files.push({
          [filename]: `${ctx.request.header.host}/public/images/${filename}`,
        });
        ctx.helper.res_success({
          files,
          fields: parts.field,
        });
      }
    }

  }
}

module.exports = FileController;
